package com.example.repair

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.RepairBeanItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.RequestType
import com.example.base.mvi.UiState
import com.example.repair.adapter.RepairAdapter
import com.example.repair.databinding.ActivityRepairBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/repair/RepairActivity")
@AndroidEntryPoint
class RepairActivity : BaseActivity<ActivityRepairBinding, RepairIntent, RepairViewModel>() {
    override val binding by lazy {
        ActivityRepairBinding.inflate(layoutInflater)
    }
    override val vm by viewModels<RepairViewModel>()

    val repairAdapter by lazy { RepairAdapter() }
    var list = mutableListOf<RepairBeanItem>()
    var flag=false//降序
    var type = ""
    var position = 0
    override fun initView() {
        binding.rvRepair.adapter = repairAdapter
        binding.rvRepair.layoutManager = LinearLayoutManager(this)

        //获取维修列表
        vm.sendIntent(RepairIntent.getRepairs)

        //点击头部
        binding.headRepair.apply {
            //点击返回，退出
            headBack.setOnClickListener {
                finish()
            }
            //更改页面标题
            headTitle.setText("维修管理")
            //跳转至添加
            headAdd.setOnClickListener {
                ARouter.getInstance().build("/repair/RepairAddActivity").navigation()
            }
        }

        //跳转至维修详情
        repairAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/repair/RepairApproveActivity")
//                .withSerializable("repair",repairAdapter.data.get(position))
                .withString("rid",repairAdapter.data.get(position).id.toString())
                .navigation()
        }

        //点击升序/降序排列(根据时间)
        binding.repairOrder.setOnClickListener {
            if (flag) {//升序
                repairAdapter.data.sortBy { it.repairTime }
                binding.repairOrderiv.setImageResource(R.drawable.ic_action_asc)
                flag = false
            } else {//降序
                repairAdapter.data.sortBy { it.repairTime }
                binding.repairOrderiv.setImageResource(R.drawable.ic_action_down)
                flag = true
            }

            repairAdapter.notifyDataSetChanged()
        }

        //搜索
        binding.btnSearch.setOnClickListener {
            val content = binding.repairSv.text.toString()
            if (type.isEmpty()) {//根据工单号获取报修工单
                vm.sendIntent(RepairIntent.getRepairByNum(content))
            } else {//根据报修人查询报修工单
                vm.sendIntent(RepairIntent.getRepairByUser(content))
            }
        }

        binding.repairSv.addTextChangedListener {
            object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    //输入框为空时，自动填充列表
                    if (s.isNullOrEmpty()) {
                        repairAdapter.data.clear()
                        repairAdapter.addData(list)
                        repairAdapter.notifyDataSetChanged()
                    }
                }

                override fun afterTextChanged(s: Editable?) {

                }

            }
        }

        binding.repairFilter.setOnClickListener {
            type = "user"
        }

        //滑动删除
        val touch = ItemTouchHelper(object :
            ItemTouchHelper.SimpleCallback(ItemTouchHelper.LEFT, ItemTouchHelper.LEFT) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                position = viewHolder.adapterPosition
                vm.sendIntent(RepairIntent.deleteRepair(repairAdapter.data.get(position)?.id!!))
            }

        })
        touch.attachToRecyclerView(binding.rvRepair)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.REPIRITM -> {
                                repairAdapter.data.clear()
                                val items = it.data as RepairBeanItem
                                repairAdapter.addData(items)
                                repairAdapter.notifyDataSetChanged()
                            }

                            RequestType.DEFAULT -> {
                                repairAdapter.data.clear()
                                list.clear()
                                val items = it.data as Collection<RepairBeanItem>
                                list.addAll(items)
                                Log.i("lr", items.toString())
                                repairAdapter.addData(items)
                                repairAdapter.notifyDataSetChanged()
                            }
                            RequestType.DELETE-> {
                                ToastUtils.showLong("删除成功")
                                vm.sendIntent(RepairIntent.getRepairs)
                            }
                            else -> {}
                        }
                    }
                    is UiState.onError->{
                        Log.i("lr",it.msg)
                    }
                    else->{}
                }
            }
        }
    }
    override fun onResume() {
        super.onResume()
        vm.sendIntent(RepairIntent.getRepairs)
    }
}